﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using static System.Threading.Thread;
using static System.Console;
using KongMing.Common;

namespace Project_4
{
    public class Unit_4_07:UnitBase
    {
        public static void Go()
        {
            var cts=new CancellationTokenSource();
            var longTask=new Task<int>(() => TaskMethod("Task 1", 10, cts.Token),cts.Token);
            WriteLine(longTask.Status);
            cts.Cancel();
            WriteLine(longTask.Status);
            WriteLine("第一个任务在执行前已被取消");

            cts=new CancellationTokenSource();
            longTask = new Task<int>(() => TaskMethod("Task2", 10, cts.Token), cts.Token);
            longTask.Start();

            for (int i = 0; i < 5; i++)
            {
                Sleep(TimeSpan.FromSeconds(0.5));
                WriteLine(longTask.Status);
            }
            cts.Cancel();
            for (int i = 0; i < 5; i++)
            {
                Sleep(TimeSpan.FromSeconds(0.5));
                WriteLine(longTask.Status);
            }

            WriteLine($"一个任务已经完成.Result：{longTask.Result}");
        }

        static int TaskMethod(string name,int seconds,CancellationToken token)
        {
            WriteCurrentTaskInfo(name);
            for (int i = 0; i < seconds; i++)
            {
                SleepSeconds(1);
                if (token.IsCancellationRequested) 
                    return -1;
            }

            return 42 * seconds;
        }
    }
}
